package com.gong.gongcloudpicture1.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.gong.gongcloudpicture1.common.BaseResponse;
import com.gong.gongcloudpicture1.config.CosClientConfig;
import com.gong.gongcloudpicture1.exception.BusinessException;
import com.gong.gongcloudpicture1.exception.ErrorCode;
import com.gong.gongcloudpicture1.exception.ThrowUtils;
import com.gong.gongcloudpicture1.model.dto.file.UploadPictureResult;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 编写根据业务相关的上传图片
 * @deprecated 已废弃, 改为upload包的模板方法优化
 */
@Slf4j
@Service //由于当前通用代码偏向业务, 所以这边加上该注解
@Deprecated //该注解表示已废弃当前类
public class FileManager {


    /**
     * 文件大小
     * 1M
     */
    private static final long MAX_SIZE = 1024 * 1024;


    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    /**
     * 上传文件
     * @param multipartFile 需要上传的文件
     * @param uploadPathPrefix 文件路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        //校验图片
        checkPicture(multipartFile);
        //制定图片上传地址
        String uuId = RandomUtil.randomString(16);
        String filename = multipartFile.getOriginalFilename();
        String currentDate = DateUtil.formatDate(new Date());
        //得到最终的上传路径, 文件名以及文件尾缀, 不能使用中文, 避免路径解析错误
        String filePathName = String.format("%s_%s.%s", currentDate, uuId, FileUtil.getSuffix(filename));
        //uploadPathPrefix该参数是区分不同用户数上传的图片, 每个用户都有自己的一个文件夹
        String filePath = String.format("/%s/%s", uploadPathPrefix, filePathName);
        //返回解析结果
        File file = null;
        try {
            //将multipartFile转换成一个临时文件
            file = File.createTempFile(filePath, null);
            //将multipartFile的内容传输到file中
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(filePath, file);
            //获取图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            //路径是COS host+上传路径
            int height = imageInfo.getHeight();
            int width = imageInfo.getWidth();
            //计算宽高比, 宽 / 高 保留两位小数
            double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + filePath);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicSize(multipartFile.getSize());
            uploadPictureResult.setPicName(FileUtil.mainName(multipartFile.getOriginalFilename()));
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到存储对象失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            //删除临时文件
            deleteTempFile(file);
        }
    }




    /**
     * 校验图片
     * @param multipartFile
     */
    private void checkPicture(MultipartFile multipartFile) {
        //判断是否为空
        ThrowUtils.throwIf(multipartFile == null, new BusinessException(ErrorCode.PARAMS_ERROR, "上传的图片不存在!"));
        //判断图片大小
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > 5 * MAX_SIZE, new BusinessException(ErrorCode.PARAMS_ERROR, "图片大小不可以超过5M!"));
        //校验文件后缀名
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> SUFFIX_LIST = Arrays.asList("jpg", "jpeg", "png", "webp");
        ThrowUtils.throwIf(!SUFFIX_LIST.contains(fileSuffix), new BusinessException(ErrorCode.PARAMS_ERROR, "仅支持jpg, png, jpeg格式的图片上传!"));
    }




    /**
     * 删除临时文件
     * @param file
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            boolean delete = file.delete();
            if (!delete) {
                log.error("file delete error" + file.getAbsolutePath());
            }
        }
    }


}
